package com.unohacha.qqj.fzdr.personal.view.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.HelpActivity;
import com.unohacha.qqj.fzdr.common.bean.HttpResult;
import com.unohacha.qqj.fzdr.common.http.RetrofitManager;
import com.unohacha.qqj.fzdr.common.utils.TemporaryDataUtil;
import com.unohacha.qqj.fzdr.personal.bean.UserInfoBean;
import com.unohacha.qqj.fzdr.my.MyInfoCenterActivity;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.personal.presenter.IPersonalPresenter;
import com.unohacha.qqj.fzdr.personal.presenter.PersonalPresenter;
import com.unohacha.qqj.fzdr.personal.view.IPersonal;
import com.unohacha.qqj.fzdr.personal.view.activity.AuthenticationCenterActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.BrowsingManagementActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.CollectionActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.MaterialQuotationActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.ReleaseManagementActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.SettingActivity;
import com.unohacha.qqj.fzdr.ui.activity.MyImgLibraryActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.mylibrary.base.BaseFragment;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主界面 我的 Fragment
 */
public class MyFragment extends BaseFragment implements IPersonal {

    private final static String TAG = "MyFragment";

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;

    @BindView(R.id.my_head_image)
    RoundedImageView myHeadImage;
    @BindView(R.id.my_username)
    TextView myUsername;
    @BindView(R.id.my_locate)
    TextView myLocate;
    @BindView(R.id.my_info_center)
    LinearLayout myInfoCenter;
    @BindView(R.id.my_wallet)
    TextView myWallet;
    @BindView(R.id.my_score)
    TextView myScore;

    @BindView(R.id.identification_center)
    TextView identificationCenter;
    @BindView(R.id.vip_center)
    TextView vipCenter;

    @BindView(R.id.publish_manager)
    LinearLayout publishManager;
    @BindView(R.id.skan_manager)
    LinearLayout skanManager;
    @BindView(R.id.my_collection)
    LinearLayout myCollection;
    @BindView(R.id.goods_price)
    LinearLayout goodsPrice;
    @BindView(R.id.my_dada)
    LinearLayout myDada;
    @BindView(R.id.review_make)
    LinearLayout reviewMake;
    @BindView(R.id.my_images)
    LinearLayout myImages;
    @BindView(R.id.cantact_us)
    LinearLayout cantactUs;
    @BindView(R.id.idea)
    LinearLayout idea;
    @BindView(R.id.comment)
    LinearLayout comment;

    Unbinder unbinder;

    private IPersonalPresenter iPersonalPresenter;

    @Override
    protected void initBundle(Bundle arguments) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_layout;
    }

    @Override
    protected void initView(View rootView) {
        commonBack.setVisibility(View.INVISIBLE);
        commonTitle.setText("我的");
        commonRightImage.setImageResource(R.drawable.ic_setting);
        // 初始化 我的 逻辑类
        iPersonalPresenter = new PersonalPresenter(this);
        Log.d("Token:", Prefer.getInstance().getToken());
    }


    @Override
    protected void initData() {
        // 获取用户信息
        iPersonalPresenter.getUserInfo(Prefer.getInstance().getToken());


    }

    private String tel = "";


    @OnClick({R.id.my_info_center, R.id.my_wallet, R.id.my_score,
            R.id.identification_center, R.id.vip_center, R.id.publish_manager,
            R.id.skan_manager, R.id.my_collection, R.id.goods_price, R.id.my_dada,
            R.id.review_make, R.id.my_images, R.id.cantact_us, R.id.idea,
            R.id.comment, R.id.common_right_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_info_center:
                jumpToOtherActivity(getContext(), MyInfoCenterActivity.class);
                break;
            case R.id.my_wallet: // 我的钱包
//                jumpToOtherActivity(getContext(), WalletActivity.class);
                Toast.makeText(getContext(), "我的钱包功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.my_score: // 个人积分
                Toast.makeText(getContext(), "个人积分功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.identification_center: // 认证中心
                jumpToOtherActivity(getContext(), AuthenticationCenterActivity.class);
                break;
            case R.id.vip_center: // 会员中心
                Toast.makeText(getContext(), "会员中心功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.publish_manager: // 发布管理
                jumpToOtherActivity(getContext(), ReleaseManagementActivity.class);
                break;
            case R.id.skan_manager: // 浏览管理
                ToastUtil.showCustomToast("浏览管理功能还在开发中");
              //  jumpToOtherActivity(getContext(), BrowsingManagementActivity.class);
                break;
            case R.id.my_collection: // 我的收藏
                ToastUtil.showCustomToast("我的收藏功能还在开发中");
              //  jumpToOtherActivity(getContext(), CollectionActivity.class);
                break;
            case R.id.goods_price: // 物资报价
                ToastUtil.showCustomToast("物资报价功能还在开发中");
          //      jumpToOtherActivity(getContext(), MaterialQuotationActivity.class);
                break;
            case R.id.my_dada: // 我的数据
                Toast.makeText(getContext(), "我的数据功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.review_make: // 预约加工
                Toast.makeText(getContext(), "预约加工功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.my_images: // 我的图库
//                jumpToOtherActivity(getContext(), MyImageStoreActivity.class);
                Intent intent=new Intent(getContext(), MyImgLibraryActivity.class);
//                intent.putExtra("typeid",Integer.valueOf(typeId));
//                intent.putExtra("id",Integer.valueOf(mId));
                startActivity(intent);
                break;
            case R.id.cantact_us: // 联系客服
                Call<HttpResult<String>> call = RetrofitManager.getInstance().contactService();
                call.enqueue(new Callback<HttpResult<String>>() {
                    @Override
                    public void onResponse(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                        String data = response.body().getTel();
                        if (data != null) {
                            tel = data;
                            Log.d(TAG, "call: " + tel);
                            new AlertDialog.Builder(getContext())
                                    .setTitle("拨打客服电话")
                                    .setMessage("客服电话：" + data)
                                    .setCancelable(false)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                        }
                                    })
                                    .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            call();
                                            dialog.cancel();
                                        }
                                    }).create().show();
                        }
                    }

                    @Override
                    public void onFailure(Call<HttpResult<String>> call, Throwable t) {

                    }
                });
                break;
            case R.id.idea: // 帮助与反馈
                jumpToOtherActivity(getContext(), HelpActivity.class);
                break;
            case R.id.comment: // 欢迎评价
                Toast.makeText(getContext(), "欢迎评价功能还在开发中", Toast.LENGTH_SHORT).show();
                break;
            case R.id.common_right_image://设置
                jumpToOtherActivity(getContext(), SettingActivity.class);
                break;
        }
    }

    // 拨打客服
    private void call() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + "18158659509");
        intent.setData(data);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.CALL_PHONE}, 100001);
            return;
        }
        getContext().startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 100001) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //执行自己的业务逻辑
                call();
            } else {
                Toast.makeText(getContext(), "拒绝了权限", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void showUserInfo(UserInfoBean userInfoBean) {
        // 显示个人信息
        if (userInfoBean.getThumb() != null && !userInfoBean.getThumb().toString().equals("")) { // 头像
            Glide.with(this).load(userInfoBean.getThumb()).into(myHeadImage);
        } else {
            Glide.with(this).load(R.drawable.ic_default_photo).into(myHeadImage);
        }
        myUsername.setText(userInfoBean.getTelephone());

        // 保存登录信息
        TemporaryDataUtil.setUserInfoBean(userInfoBean);

    }
}
